<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { Message, Modal } from '@arco-design/web-vue'
import { updateUser, changePassword } from '@/api/user'
import { useUserStore } from '@/stores/user'
import type { User } from '@/api/user'

const router = useRouter()
const userStore = useUserStore()
const loading = ref(false)
const editMode = ref(false)

// 用户信息表单
const userForm = reactive<Partial<User>>({
  username: '',
  nickname: '',
  phone: '',
  email: '',
  avatar: '',
  gender: 1,
  address: ''
})

// 修改密码表单
const passwordForm = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 修改密码对话框
const passwordModalVisible = ref(false)

// 初始化数据
onMounted(async () => {
  loading.value = true
  try {
    // 如果store中没有用户信息，则获取
    if (!userStore.currentUser) {
      await userStore.fetchCurrentUser()
    }
    
    // 如果获取失败或仍然没有用户信息，跳转到登录页
    if (!userStore.currentUser) {
      throw new Error('获取用户信息失败')
    }
    
    // 初始化表单数据
    Object.assign(userForm, {
      username: userStore.currentUser.username,
      nickname: userStore.currentUser.nickname,
      phone: userStore.currentUser.phone,
      email: userStore.currentUser.email,
      avatar: userStore.currentUser.avatar,
      gender: userStore.currentUser.gender,
      address: userStore.currentUser.address
    })
  } catch (error) {
    console.error('获取用户信息失败:', error)
    Message.error('获取用户信息失败，请稍后再试')
    
    // 如果获取用户信息失败，可能是token无效，跳转到登录页
    router.push('/login')
  } finally {
    loading.value = false
  }
})

// 切换编辑模式
const toggleEditMode = () => {
  if (editMode.value) {
    // 取消编辑，恢复原始数据
    if (userStore.currentUser) {
      Object.assign(userForm, {
        username: userStore.currentUser.username,
        nickname: userStore.currentUser.nickname,
        phone: userStore.currentUser.phone,
        email: userStore.currentUser.email,
        avatar: userStore.currentUser.avatar,
        gender: userStore.currentUser.gender,
        address: userStore.currentUser.address
      })
    }
  }
  
  editMode.value = !editMode.value
}

// 保存用户信息
const saveUserInfo = async () => {
  if (!userStore.currentUser) return
  
  // 确保包含用户名
  if (!userForm.username) {
    userForm.username = userStore.currentUser.username
  }
  
  console.log('保存用户信息:', userForm)
  
  loading.value = true
  try {
    const response = await updateUser(userStore.currentUser.id, userForm)
    console.log('更新用户信息响应:', response)
    
    if (response.code === 200) {
      // 更新store中的用户数据
      await userStore.fetchCurrentUser()
      
      Message.success('保存成功')
      editMode.value = false
    } else {
      throw new Error(response.message || '保存失败')
    }
  } catch (error: any) {
    console.error('保存用户信息失败:', error)
    Message.error('保存用户信息失败: ' + (error.message || '请稍后再试'))
  } finally {
    loading.value = false
  }
}

// 打开修改密码对话框
const openPasswordModal = () => {
  passwordForm.oldPassword = ''
  passwordForm.newPassword = ''
  passwordForm.confirmPassword = ''
  passwordModalVisible.value = true
}

// 提交修改密码
const submitChangePassword = async () => {
  if (!userStore.currentUser) return
  
  // 验证新密码
  if (passwordForm.newPassword !== passwordForm.confirmPassword) {
    Message.error('两次输入的新密码不一致')
    return
  }
  
  if (passwordForm.newPassword.length < 6) {
    Message.error('新密码长度不能小于6个字符')
    return
  }
  
  console.log('修改密码参数:', {
    id: userStore.currentUser.id,
    oldPassword: passwordForm.oldPassword,
    newPassword: passwordForm.newPassword
  })
  
  loading.value = true
  try {
    const response = await changePassword(
      userStore.currentUser.id, 
      passwordForm.oldPassword, 
      passwordForm.newPassword
    )
    
    console.log('修改密码响应:', response)
    
    if (response.code === 200) {
      Message.success('密码修改成功')
      passwordModalVisible.value = false
    } else {
      throw new Error(response.message || '修改密码失败')
    }
  } catch (error: any) {
    console.error('修改密码失败:', error)
    Message.error('修改密码失败: ' + (error.message || '请检查原密码是否正确'))
  } finally {
    loading.value = false
  }
}

// 退出登录
const handleLogout = () => {
  Modal.confirm({
    title: '确认退出登录？',
    content: '退出后需要重新登录',
    onOk: () => {
      userStore.logout()
      Message.success('退出登录成功')
      router.push('/')
    }
  })
}

// 跳转到订单页面
const goToOrder = () => {
  router.push('/order')
}

// 返回首页
const goToHome = () => {
  router.push('/')
}
</script>

<template>
  <div class="user-container">
    <a-spin :loading="loading" tip="加载中...">
      <!-- 标题栏 -->
      <div class="user-header">
        <a-button shape="circle" @click="goToHome">
          <template #icon><icon-left /></template>
        </a-button>
        <h2>个人中心</h2>
        <div></div>
      </div>

      <div class="user-content" v-if="userStore.currentUser">
        <!-- 左侧：用户信息和功能菜单 -->
        <div class="user-left-column">
          <!-- 用户信息 -->
          <div class="user-info">
            <div class="user-avatar">
              <a-avatar :size="100">
                <template #icon><icon-user /></template>
              </a-avatar>
            </div>
            <div class="user-name">{{ userStore.currentUser.nickname || userStore.currentUser.username }}</div>
            <div class="user-id">ID: {{ userStore.currentUser.id }}</div>
          </div>

          <!-- 功能菜单 -->
          <div class="user-menu">
            <a-list>
              <a-list-item @click="goToOrder">
                <template #extra><icon-right /></template>
                <a-list-item-meta>
                  <template #icon><icon-calendar /></template>
                  <template #title>我的订单</template>
                  <template #description>查看历史订单</template>
                </a-list-item-meta>
              </a-list-item>
              
              <a-list-item @click="openPasswordModal">
                <template #extra><icon-right /></template>
                <a-list-item-meta>
                  <template #icon><icon-lock /></template>
                  <template #title>修改密码</template>
                  <template #description>更新账号密码</template>
                </a-list-item-meta>
              </a-list-item>
              
              <a-list-item @click="handleLogout">
                <template #extra><icon-right /></template>
                <a-list-item-meta>
                  <template #icon><icon-export /></template>
                  <template #title>退出登录</template>
                  <template #description>退出当前账号</template>
                </a-list-item-meta>
              </a-list-item>
            </a-list>
          </div>
        </div>

        <!-- 右侧：用户详细信息 -->
        <div class="user-right-column">
          <!-- 用户详细信息 -->
          <div class="user-detail">
            <div class="detail-header">
              <h3>个人信息</h3>
              <a-button
                type="outline"
                :status="editMode ? 'danger' : 'normal'"
                @click="toggleEditMode"
              >
                {{ editMode ? '取消' : '编辑' }}
              </a-button>
            </div>

            <a-form
              :model="userForm"
              layout="vertical"
            >
              <!-- 隐藏的用户名字段 -->
              <a-form-item field="username" class="hidden-field">
                <a-input
                  v-model="userForm.username"
                  readonly
                  style="display: none;"
                />
              </a-form-item>
              
              <a-row :gutter="16">
                <a-col :span="12">
                  <a-form-item field="nickname" label="昵称">
                    <a-input
                      v-model="userForm.nickname"
                      placeholder="请输入昵称"
                      :readonly="!editMode"
                    />
                  </a-form-item>
                </a-col>
                
                <a-col :span="12">
                  <a-form-item field="phone" label="手机号">
                    <a-input
                      v-model="userForm.phone"
                      placeholder="请输入手机号"
                      :readonly="!editMode"
                    />
                  </a-form-item>
                </a-col>
              </a-row>
              
              <a-form-item field="email" label="邮箱">
                <a-input
                  v-model="userForm.email"
                  placeholder="请输入邮箱"
                  :readonly="!editMode"
                />
              </a-form-item>
              
              <a-form-item field="gender" label="性别">
                <a-radio-group v-model="userForm.gender" :disabled="!editMode">
                  <a-radio :value="1">男</a-radio>
                  <a-radio :value="2">女</a-radio>
                  <a-radio :value="0">保密</a-radio>
                </a-radio-group>
              </a-form-item>
              
              <a-form-item field="address" label="地址">
                <a-input
                  v-model="userForm.address"
                  placeholder="请输入地址"
                  :readonly="!editMode"
                />
              </a-form-item>
              
              <a-button
                v-if="editMode"
                type="primary"
                long
                @click="saveUserInfo"
              >
                保存
              </a-button>
            </a-form>
          </div>
        </div>
      </div>
    </a-spin>

    <!-- 修改密码对话框 -->
    <a-modal
      v-model:visible="passwordModalVisible"
      title="修改密码"
      @cancel="passwordModalVisible = false"
      @ok="submitChangePassword"
    >
      <a-form :model="passwordForm" layout="vertical">
        <a-form-item field="oldPassword" label="原密码">
          <a-input-password
            v-model="passwordForm.oldPassword"
            placeholder="请输入原密码"
            allow-clear
          />
        </a-form-item>
        
        <a-form-item field="newPassword" label="新密码">
          <a-input-password
            v-model="passwordForm.newPassword"
            placeholder="请输入新密码"
            allow-clear
          />
        </a-form-item>
        
        <a-form-item field="confirmPassword" label="确认新密码">
          <a-input-password
            v-model="passwordForm.confirmPassword"
            placeholder="请再次输入新密码"
            allow-clear
          />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<style scoped>
.user-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
  width: 100%;
}

.user-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 30px;
}

.user-header h2 {
  margin: 0;
  font-size: 24px;
  color: var(--color-text-1);
}

.user-content {
  display: flex;
  gap: 24px;
}

/* 左侧列 */
.user-left-column {
  display: flex;
  flex-direction: column;
  gap: 24px;
  width: 300px;
  flex-shrink: 0;
}

/* 右侧列 */
.user-right-column {
  flex: 1;
}

.user-info {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 30px;
  background-color: var(--color-bg-2);
  border-radius: 12px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
}

.user-avatar {
  margin-bottom: 20px;
}

.user-name {
  font-size: 22px;
  font-weight: bold;
  margin-bottom: 10px;
  color: var(--color-text-1);
  text-align: center;
}

.user-id {
  font-size: 14px;
  color: var(--color-text-3);
}

.user-detail {
  padding: 24px;
  background-color: var(--color-bg-2);
  border-radius: 12px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
  height: 100%;
}

.detail-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.detail-header h3 {
  margin: 0;
  font-size: 18px;
  color: var(--color-text-1);
}

.user-menu {
  background-color: var(--color-bg-2);
  border-radius: 12px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
  overflow: hidden;
}

/* 响应式布局 */
@media (max-width: 768px) {
  .user-container {
    padding: 16px;
  }
  
  .user-content {
    flex-direction: column;
  }
  
  .user-left-column {
    width: 100%;
  }
  
  .user-info,
  .user-detail,
  .user-menu {
    padding: 16px;
  }
}

/* 表单样式优化 */
:deep(.arco-form-item) {
  margin-bottom: 20px;
}

:deep(.arco-input),
:deep(.arco-input-password) {
  border-radius: 6px;
}

:deep(.arco-radio-group) {
  display: flex;
  gap: 16px;
}

/* 按钮样式优化 */
:deep(.arco-btn) {
  border-radius: 6px;
  height: 40px;
  font-weight: 500;
}

/* 隐藏字段 */
.hidden-field {
  display: none;
}
</style> 